/*
 * PathCompleter.scala
 */

package acorn.jash

import java.io.File


/*
 * To compile successfully, the jline.jar distributed with scala distribution
 * should be used instead of that of http://jline.sourceforge.net/index.html.
 * For scala-2.8.1, the import below should be straight jline._, but for
 * scala-2.9, since jline is wrapped (or improved) in scala-tools, the import
 * should be scala.tools.jline.console.completer.
 */
// import jline._
import scala.tools.jline.console.completer._

class PathCompleter extends Completer {
  import java.util.{List => JList}

  override def complete(buf:String, cur:Int,
                        candidates:JList[CharSequence]):Int = {

    var path:Path = null;
    var mask:String = ""

    val buff = if (null == buf) "" else buf
    buff match {
      case "//" => -1
      case _ => {
        val i = buff lastIndexOf "/"
        if (i == -1) {
          path = Shell.wd
          mask = buff
        }
        else if (buff endsWith "/") {
          path = Shell.wd.changeTo(buff)
        }
        else {
          if (i == 0) path = Shell.wd.drive
          else path = Shell.wd.changeTo(buff.substring(0, i))
          mask = buff.substring(1+i)
        }

        val realpath = path.realpath
        mask = realpath + (if (mask == "") ""
                           else if (realpath endsWith "\\") mask
                           else "\\" + mask)
        matchFiles(buff, mask, path.asFile.listFiles, candidates)
      }
    }
  }

  
  private def matchFiles(buffer:String, path:String, files:Array[File],
                         candidates:JList[CharSequence]):Int = {
    if (files == null) return -1

    val matches = files.count(_.getAbsolutePath.startsWith(path))

    files.foreach{file=>
                  val matched = file.getAbsolutePath.startsWith(path)
                  if (matched) {
                    val name = file.getName + (
                      if (matches == 1 && file.isDirectory) "/" else " ")
                    candidates add name
                  }
                }
    (buffer lastIndexOf ("/")) + 1
  }
}
